package com.ruoyi.mongo.service;

import com.ruoyi.mongo.cet4.Entity4;
import com.ruoyi.mongo.cet4.EntityExpand4;
import com.ruoyi.mongo.cet4.repository.SecondaryRepository;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.ruoyi.mongo.service.MongoService.getWordChinese;
import static com.ruoyi.mongo.service.MongoService.getWordType;

@Service
public class MongoTempService {

    @Autowired
    private SecondaryRepository secondaryRepository;

    @Autowired
    private MongoService mongoService;

    public void getEntityExpandCollection(){
        List<Entity4> list = secondaryRepository.findAll();
        setEntityExpandCollection(0,list);
    }

    public void saveByGroup(int groupId) {
        List<Entity4> list = secondaryRepository.findByGroup(groupId);
        setEntityExpandCollection(groupId, list);
    }

    private void setEntityExpandCollection(int groupId, List<Entity4> list) {
        for (Entity4 entity4 : list) {
            String chinese = entity4.getChinese().trim();
            String[] strings = StringUtils.splitIntoLetterChinesePairs(chinese);
            saveEntityExpandMeaning(entity4, strings, groupId);
        }
    }

    private void saveEntityExpandMeaning(Entity4 entity, String[] strings, int groupId) {
        EntityExpand4 entityExpand4 = new EntityExpand4();
        BeanUtils.copyProperties(entity, entityExpand4);
        for (String byIndex : strings) {
            String wordMeaning = byIndex.trim();
            entityExpand4.setWordMeaning(wordMeaning);
            entityExpand4.setMeaning(getWordChinese(wordMeaning));
            String[] wordType = getWordType(wordMeaning);
            for (String type : wordType) {
                entityExpand4.set_id(null);
                entityExpand4.setType(type.trim().replace(".", ""));
                if (groupId != 0) {
                    mongoService.saveToSecondary(entityExpand4, groupId);
                }
                else {
                    mongoService.saveToSecondary(entityExpand4);
                }
            }
        }
    }
}
